const gulp = require('gulp')
const stylus = require('gulp-stylus')
const del = require('del')
const path = require('path')
// const autoprefixer = require('gulp-autoprefixer') // 小程序暂时不需要
const cssmin = require('gulp-clean-css')
const imagemin = require('gulp-imagemin')
const rename = require('gulp-rename')

/* 定义一些常量 */
const srcPath = './src/**' 
const distPath = './dist/'
const delPath = ['dist/**/*']
const wxmlFilesPath = [`${srcPath}/*.wxml`, `!${srcPath}/_template/*.wxml`]
const stylFilesPath = [`${srcPath}/*.styl`, `!${srcPath}/styl/**/*.styl`, `!${srcPath}/_template/*.styl`]
const jsonFilesPath = [`${srcPath}/*.json`, `!${srcPath}/_template/*.json`]
const jsFilesPath = [`${srcPath}/*.js`, `!${srcPath}/_template/*.js`]
const imagesFilesPath = [
  `${srcPath}/images/*.{png,jpg,gif,ico}`,
  `${srcPath}/images/**/*.{png,jpg,gif,ico}`
]

/* 删除dist文件夹 */
gulp.task('clean', done => {
  del.sync(delPath)
  done()
})

/* 编译styl文件 */
const styl = () => {
  return gulp.src(stylFilesPath)
    .pipe(stylus())
    // .pipe(autoprefixer())
    .pipe(cssmin())
    .pipe(rename((path) => {
      path.extname = '.wxss'
    }))
    .pipe(gulp.dest(distPath))
}
gulp.task(styl)

/* 编译js文件 */
const js = () => {
  return gulp.src(jsFilesPath)
    .pipe(gulp.dest(distPath))
}
gulp.task(js)

/* 编译json文件 */
const json = () => {
  return gulp.src(jsonFilesPath)
    .pipe(gulp.dest(distPath))
}
gulp.task(json)

/* 编译wxml文件 */
const wxml = () => {
  return gulp.src(wxmlFilesPath)
    .pipe(gulp.dest(distPath))
}
gulp.task(wxml)

/* 压缩图片 */
const image = () => {
  return gulp
    .src(imagesFilesPath)
    .pipe(imagemin())
    .pipe(gulp.dest(distPath))
}
gulp.task(image)

// /* build */
gulp.task('default',
  gulp.series('clean',
    gulp.parallel('wxml', 'js', 'json', 'styl', 'image')
  )
)

/* watch */
gulp.task('watch', () => {
  gulp.watch(stylFilesPath, styl)
  gulp.watch(jsFilesPath,js)
  gulp.watch(jsonFilesPath, json)
  gulp.watch(wxmlFilesPath, wxml)
  gulp.watch(imagesFilesPath, image)
})

/* dev */
gulp.task('dev', gulp.series('default', 'watch'))
